package com.example.spring_musicserver_1113.controller;

import com.example.spring_musicserver_1113.mapper.LoveMusicMapper;
import com.example.spring_musicserver_1113.mapper.MusicMapper;
import com.example.spring_musicserver_1113.model.Music;
import com.example.spring_musicserver_1113.model.User;
import com.example.spring_musicserver_1113.tools.Constant;
import com.example.spring_musicserver_1113.tools.ResponseBodyMessage;
import org.apache.ibatis.binding.BindingException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.net.BindException;
import java.nio.file.Files;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * @version 1.0
 * @Author 作者名
 * @Date 2024/11/14 13:19
 * @注释
 */
@RestController
@RequestMapping("/music")
public class MusicController {
    @Autowired
    private LoveMusicMapper loveMusicMapper;

    @Autowired
    private MusicMapper musicMapper;
    @Value("${music.local.path}")
    private String SAVE_PATH;
            //="D:/music/";

    @RequestMapping("/upload")
    public ResponseBodyMessage<Boolean> insertMusic(@RequestParam String singer,
                                                    @RequestParam("filename") MultipartFile file, HttpServletRequest request,
                                                    HttpServletResponse response) throws IOException {
        //1、判断登录情况
        HttpSession httpSession = request.getSession(false);
        if(httpSession == null || httpSession.getAttribute(Constant.USERINFO_SESSION_KEY) == null){
            System.out.println("没有登录！");
            return new ResponseBodyMessage<>(-1,"请登录后上传",false);
        }
        //1.1、在一首歌曲上传到服务器之前，查询当前数据库中是否有当前音乐：title+singer

        //2、上传到服务器
        String fileNameAndType = file.getOriginalFilename();
        System.out.println("fileNameAndType"+fileNameAndType);
        String path = SAVE_PATH + "/"+fileNameAndType;
        File dest = new File(path);
        if(!dest.exists()){
            dest.mkdir();
        }
        try {
            file.transferTo(dest);
//            return new ResponseBodyMessage<>(0,"上传成功",true);
        } catch (IOException e) {
            e.printStackTrace();
            return new ResponseBodyMessage<>(-1,"服务器上传失败",false);
        }

        //3、进行数据库的上传
        //准备数据
        int index = fileNameAndType.lastIndexOf(".");
        //对于文件名，从后往前扫描，找到第一个。
        String title = fileNameAndType.substring(0,index);
        User user = (User) httpSession.getAttribute(Constant.USERINFO_SESSION_KEY);
        int userid = user.getId();
        //播放音乐的时候就会发出一个http请求
        String url = "/music/get?path="+title;
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
        String time = sf.format(new Date());
        //调用insert
        try{
            int ret = 0;
            ret = musicMapper.insert(title,singer,time,url,userid);
            if (ret == 1){
                response.sendRedirect("/list.html");
                return new ResponseBodyMessage<>(0,"数据库上传成功",true);
            }else {
                return new ResponseBodyMessage<>(-1,"数据库上传失败",false);
            }
        }catch (BindingException e){
            dest.delete();
            return new ResponseBodyMessage<>(-1,"数据库上传失败",false);
        }
        //新的问题，如果重复传输一首歌的讨论
    }

    @RequestMapping("/get")
    public ResponseEntity<byte[]> get(String path){
        File file = new File(SAVE_PATH+"/"+path);
        byte[] a= null;
        try {
            a = Files.readAllBytes(file.toPath());
            if(a == null){
                return ResponseEntity.badRequest().build();
            }
            return ResponseEntity.ok(a);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return ResponseEntity.badRequest().build();
    }

    /**
     * 删除单个音乐
     * @param id
     * @return
     */
    @RequestMapping("/delete")
    public ResponseBodyMessage<Boolean> deleteMusicById(@RequestParam String id){
        //1、检查当前ID的音乐是否存在
        int iid = Integer.parseInt(id);
        //2、如果当前ID音乐存在的话就要删除
        Music music = musicMapper.findMusicById(iid);
        if(music == null){
            System.out.println("没有查询到当前id的音乐");
            return new ResponseBodyMessage<>(-1,"没有查询到当前id的音乐",false);
        }else {
            //2.1 删除数据路
            int ret = musicMapper.deleteMusicById(iid);
            if(ret == 1){
                //2.2 删除服务器上的数据
                int index = music.getUrl().lastIndexOf("=");
                String fileName = music.getUrl().substring(index+1);
                File file = new File(SAVE_PATH+"/"+fileName+".mp3");
                System.out.println("当前的路径"+file.getPath());
                if (file.delete()){
                    //同步删除lovemusic表中的该音乐
                    loveMusicMapper.deleteLoveMusicByMusicId(iid);
                    return new ResponseBodyMessage<>(0,"服务器中的音乐删除成功",true);
                }else {
                   return   new ResponseBodyMessage<>(-1,"服务器中的音乐删除失败",false);
                }

            }else {
                return new ResponseBodyMessage<>(-1,"数据库当中的音乐没有删除成功",false);
            }
        }
    }

    /**
     * 批量删除音乐
     * @param id
     * @return
     */
    @RequestMapping("/deleteSel")
    public ResponseBodyMessage<Boolean> deleteSelMusic(@RequestParam("id[]")
                                                       List<Integer> id){
        System.out.println("所有的id"+ id);
        int sum = 0;
        for (int i = 0; i < id.size(); i++) {
            Music music = musicMapper.findMusicById(id.get(i));
            if(music == null){
                System.out.println("没有查询到当前id的音乐");
                return new ResponseBodyMessage<>(-1,"没有查询到当前id的音乐",false);
            }
            int ret = musicMapper.deleteMusicById(id.get(i));
            if(ret == 1) {
                int index = music.getUrl().lastIndexOf("=");
                String fileName = music.getUrl().substring(index + 1);
                File file = new File(SAVE_PATH + "/" + fileName + ".mp3");
                if (file.delete()) {
                    //同步删除lovemusic表中的该音乐
                    loveMusicMapper.deleteLoveMusicByMusicId(id.get(i));
                    sum += ret;
                } else {
                    return new ResponseBodyMessage<>(-1, "服务器中的音乐删除失败", false);
                }
            }else {
                return new ResponseBodyMessage<>(-1,"数据库当中的音乐没有删除成功",false);
            }
        }
        if(sum == id.size()){

            System.out.println("批量删除成功");
            return new ResponseBodyMessage<>(0,"音乐批量删除成功",true);
        }else {
            System.out.println("批量删除失败");
            return   new ResponseBodyMessage<>(-1,"音乐批量删除失败",false);
        }
    }

    @RequestMapping("/findmusic")
    public ResponseBodyMessage<List<Music>> findMusic(
            @RequestParam(required = false) String musicName){
        List<Music> musicList = null;
        if(musicName != null){
            musicList = musicMapper.findMusicByName(musicName);
        }else {
            musicList = musicMapper.findMusic();
        }
        return new ResponseBodyMessage<>(0,"查询到了当前的所有音乐",musicList);
    }
}
